<template>
<div class="contain">
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <header class="hd-top">
    <span class="iconfont icon-left" @click="goBack"></span>
    <h2 class="title">新增地址</h2>
    <button class="btn" @click="save">保存</button>
  </header>
  <div class="page">
    <div class="form-box displayflex">
      <div class="label">联系人</div>
      <div class="ctx flex1">
        <input type="text" class="txt-rit" placeholder="请输入" v-model="Contacts">
      </div>
    </div>
    <div class="form-box displayflex">
      <div class="label">联系电话</div>
      <div class="ctx flex1">
        <input type="text" class="txt-rit" placeholder="请输入" v-model="ContactsTel">
      </div>
    </div>
    <div class="displayflex form-box mb0 lineb">

      <x-address class="address-wrap" title="省市区" v-model="addressValue" :list="addressData" placeholder="请选择" value-text-align="right">
      </x-address>

      <div style="display:none" id="addressChinese">{{addressValue[0] | province}}/{{addressValue[1] | city}}/{{addressValue[2] | district}}</div>
      <i class="iconfont icon-right"></i>
    </div>

    <div class="form-box displayflex">
      <div class="label">详细地址</div>
      <div class="ctx flex1">
        <textarea placeholder="支持地址联想啦~直接输入目的地试试？" id="pickerInput" 
          v-model="Address"
          @input="getAmapPOI"
          @blur="clearResult"></textarea>
      </div>
    </div>
    <div class="picker-result">
      <div v-for="item in pickerResultList" class="pr-list">
        <div @click="selectResult(item)" class="pr-li">
          <div class="name">{{item.name}}</div>
          <div class="addr" v-if="item.address && item.address.length>0">{{item.address}}</div>
          <div class="addr" v-else>{{item.district}}</div>
        </div>
      </div>
    </div>
    <div class="form-box displayflex" v-if="type == 2">
      <div class="label">消毒截止时间</div>
      <div class="ctx flex1 txt-rit">
        <datetime v-model="valueStart1" 
          format="HH:mm:ss"
          hour-row="{value}点" minute-row="{value}分">{{valueStart1}}</datetime>
      </div>
      <i class="iconfont icon-right"></i>
    </div>

  </div>
  <div @click="save" class="btn-bottom"><div class="btn">确定</div></div>
</div>
</template>

<script>
import {
  iosProvinces,
  iosCitys,
  iosCountys
} from "@/components/share/area/areaData_v2.js";

export default {
  name:'addressForm',
  data() {
    return {
      addressValue: [],
      addressData: [],
      Contacts: "",
      ContactsTel: "",
      Address: "",
      valueStart1: "请选择",
      showLoad: false,
      hasAccount: false,
      openAccount:false,
      userbiztype:'',
      //自动联想地址结果yuyu
      pickerResultList:[]
    };
  },
  computed: {
    userinfo() {
      if (localStorage.UserInfo) {
        return JSON.parse(localStorage.UserInfo);
      }
    },
    type(){
      return this.$route.query.type;
    },
    id(){
      return this.$route.query.AddressGuid;
    },
    mine(){
      return this.$route.query.mine;
    }
  },
  watch:{
    valueStart1(n,o){
      this.valueStart1 = n.replace(':ss','');
    },
  },
  created() {
    this.getData();
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    getData() {
      this.addressData = this.ChinaAddressV3Data;
      var self = this;
      var id = this.$route.query.AddressGuid;
      if (id) {
        var query = {
          Guid: id
        };
        this.showLoad = true;
        this.Ajax.post("SearchGuidCustomerAddress", query).then(function(resp) {
          self.showLoad = false;
          var cus = resp.Data;
          self.Contacts = cus.Contacts;
          self.ContactsTel = cus.ContactsTel;
          self.Address = cus.Address;
          self.addressValue.push(self.province(cus.Province));
          self.addressValue.push(self.city(cus.City));
          self.addressValue.push(self.district(cus.District));
          if(cus.SterilizeTime != null && cus.SterilizeTime != '')
          {
            self.valueStart1 = cus.SterilizeTime;
          }
          if(cus.StaffID)
          {
            self.hasAccount = true;
          }
        });
      }
      else {
        //获取当前位置
        var options = {
            city: "" //城市，默认全国  
        };
        var geolocation = new AMap.Geolocation(options);
        geolocation.getCurrentPosition(function(status,result){
          if(status = "complete" && result.addressComponent){
            console.log(status,123,result)
            var ftp = self.$options.filters["TextProvince"],
                ftc = self.$options.filters["TextCity"],
                ftd = self.$options.filters["TextDistrict"];
            var province = ftp(result.addressComponent.province),
                city = ftc(result.addressComponent.city),
                district = ftd(result.addressComponent.district);
            self.addressValue=[province,city,district];
          };
        });
      }
    },
    //清除自动联想地址结果yuyu
    clearResult(){
      var targetResult = document.querySelectorAll(".amap-sug-result");
      for(var i = 0 ;i<targetResult.length;i++){
        targetResult[i].parentNode.removeChild(targetResult[i])
      }
      this.pickerResultList = [];
    },
    //选择自动联想地址结果yuyu
    selectResult(item){
      this.Address = item.address+item.name;
      this.clearResult();
    },
    //获取自动联想地址结果yuyu
    getAmapPOI(){
      if(!this.Address){
        this.clearResult();
        return false;
      }
      //输入提示
      var autoOptions = {
          input: "pickerInput",
          outPutDirAuto:false,
          city: this.addressValue[1] //城市，默认全国  
      };
      var self = this;
      var auto = new AMap.Autocomplete(autoOptions);

      auto.search(self.Address, function(status, result) {
        // 搜索成功时，result即是对应的匹配数据
        if(status == "complete" && self.Address){
          self.pickerResultList = result.tips
        }else if(status == "error"){
          self.clearResult();
        };
      });
    },

    province(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosProvinces.length; i++) {
          if (iosProvinces[i].id == val) {
            return iosProvinces[i].value;
          }
        }
      }
    },
    city(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosCitys.length; i++) {
          if (iosCitys[i].id == val) {
            return iosCitys[i].value;
          }
        }
      }
    },
    district(val) {
      var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(val)) {
        return val;
      }
      if (val && val != null && val != "undefined") {
        for (var i = 0; i < iosCountys.length; i++) {
          if (iosCountys[i].id == val) {
            return iosCountys[i].value;
          }
        }
      }
    },
    save() {
      var self = this,
          ftp = self.$options.filters["TextProvince"],
          ftc = self.$options.filters["TextCity"],
          ftd = self.$options.filters["TextDistrict"];
      if (!self.Contacts) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入联系人名称！"
        });
        return false;
      }
      if (!self.ContactsTel) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入联系人电话！"
        });
        return false;
      }
      var testTel = /^1[345789]\d{9}$/;
      if (!self.ContactsTel || !testTel.test(self.ContactsTel)) {
          self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入正确格式的手机号"
        });
        return false;
      }
      if (!self.addressValue[0]) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择省份！"
        });
        return false;
      }
      if (!self.addressValue[1]) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择城市！"
        });
        return false;
      }
      if (!self.addressValue[2]) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请选择区域！"
        });
        return false;
      }
      if (!self.Address) {
        self.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "请输入详情地址！"
        });
        return false;
      }
      // if(this.userinfo.TenantGuid != "20180515102052060001"){
        if(self.addressValue[0] !="530000"){
          self.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: "暂时只支持云南地区，其他地区暂未开放"
          });
          return false;
        }
      // } 
      this.doPost();
      // var content = '';
      // if(this.type == 1)
      // {
      //   self.userbiztype = 'warehouse';
      //   content = '是否同时开通仓管员账户？';
      // }
      // if(this.type == 2)
      // {
      //   self.userbiztype = 'Cargoreceiver';
      //   content = '是否同时开通收货员账户？';
      // }

      // this.$vux.confirm.show({``
      //   title:'提示',
      //   content: content,
      //   onConfirm () {
      //     alert(2)
      //     self.openAccount = true;
      //     self.doPost();
      //   },
      //   onCancel (){
      //     alert(1)
      //     self.doPost();
      //   }
      // });
    },

    doPost(){
      var self = this;
      this.showLoad = true;
      var types = this.$route.query.type;
      var id = this.$route.query.AddressGuid;
      var query = {
        CcGuid: this.userinfo.StaffID,
        Province: self.addressValue[0],
        City: self.addressValue[1],
        District: self.addressValue[2],
        Address: self.Address,
        Contacts: self.Contacts,
        ContactsTel: self.ContactsTel,
        IsChecked: "Y",
        LoginedStaffID: this.userinfo.StaffID,
        LoginedName: this.userinfo.Name,
        type: types,
        Venue: document.getElementById('addressChinese').innerHTML,
      };
      if(this.valueStart1 != '请选择'){
        query.SterilizeTime = this.valueStart1;
      }

      if (id) {
        query.Guid = id;
        query.IsDeleted = "N";
      }

      if(this.openAccount) {
        query.UserBizType = this.userbiztype;
        query.BizState = 'Y';
        query.TenantGuid = this.userinfo.TenantGuid;
        query.CorpGuid = this.userinfo.CorpGuid;
        query.CorpName = this.userinfo.CorpName;
        query.AreaFullText = document.getElementById('addressChinese').innerHTML;
      }
      
      this.Ajax.post("OperateCustomerAddressAPI", query).then(function(resp) {
        self.showLoad = false;
        if (resp.IsSuccess) {
          self.$vux.toast.show({
            type: "success", //success, warn, cancel, text
            text: "保存成功！"
          });
          var query = self.$route.query;
          query.mine = self.$route.query.mine
          self.$router.push({
            path: "/address",
            query: query
          });
        } 
        else 
        {
          self.$vux.toast.show({    
            type: "warn", //success, warn, cancel, text
            text: resp.ErrorMessage,
          });
        }
      });
    },
  }
};
</script>